<script setup lang="ts">
import { computed, ref } from 'vue';
import { useMessage } from 'naive-ui';
import { $t } from '@/locales';

interface Props {
  initialEmail?: string;
}

interface Emits {
  (e: 'next', email: string): void;
}

const props = withDefaults(defineProps<Props>(), {
  initialEmail: ''
});

const emit = defineEmits<Emits>();
const email = ref(props.initialEmail);
const error = ref('');
const loading = ref(false);
const showDialog = ref(false);

const isValidEmail = computed(() => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email.value);
});

const message = useMessage();

const handleSubmit = async () => {
  if (!isValidEmail.value) {
    message.error($t('form.email.invalid'));
    return;
  }

  loading.value = true;
  try {
    emit('next', email.value);
  } catch (err: unknown) {
    message.error(err instanceof Error ? err.message : $t('page.resetPassword.failed'));
  } finally {
    loading.value = false;
  }
};

const handleResend = async () => {
  showDialog.value = false;
  await handleSubmit();
};
</script>

<template>
  <div class="email-step">
    <NInput v-model:value="email" size="large" :placeholder="$t('form.email.required')" @keyup.enter="handleSubmit">
      <template #suffix>
        <NIcon v-if="isValidEmail" class="text-success">
          <i class="fas fa-check-circle" />
        </NIcon>
      </template>
    </NInput>

    <NButton
      class="mt-4"
      type="primary"
      block
      :disabled="!isValidEmail || loading"
      :loading="loading"
      @click="handleSubmit"
    >
      {{ $t('common.sendCode') }}
    </NButton>
  </div>
</template>
